﻿#include "http.h"
#include <QEventLoop>
#include <QtNetwork/QNetworkAccessManager>
#include <QtNetwork/QNetworkRequest>
#include <QtNetwork/QNetworkReply>
#include <QtWidgets/QWidget>
#include <QTextCodec>
#include <QString>
#include <QUrl>
#include <QJsonParseError>
#include <QJsonObject>
#include <QRegExp>
#include <QRegularExpression>

#pragma execution_character_set("utf-8")

http::http(){
   // db=Tempdb;
   db=NULL;
}

QByteArray http::get(const QString &strUrl)

{

    const QUrl url = QUrl::fromUserInput(strUrl);

    QNetworkAccessManager m_qnam;

    QNetworkRequest qnr(url);

    QNetworkReply* reply = m_qnam.get(qnr); //m_qnam是QNetworkAccessManager对象

    QEventLoop eventLoop;

    connect(reply, &QNetworkReply::finished, &eventLoop, &QEventLoop::quit);

    eventLoop.exec(QEventLoop::ExcludeUserInputEvents);

    QByteArray replyData = reply->readAll();

    int statusCode = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();

    QVariant redirectAttr = reply->attribute(QNetworkRequest::RedirectionTargetAttribute);

    if (reply->error()

            || 300 == statusCode //状态码300 Multiple Choices，既不是错误也不算重定向，应该是qt bug

            || !redirectAttr.isNull())

    {

        QString errString = reply->error() ? reply->errorString() : QString("发生重定向(%1)，不允许此情况").arg(statusCode);

        qDebug()<<QString("发送get请求时出现错误：\n网址：%1\n错误信息：%2").arg(reply->request().url().toDisplayString(), errString);

        replyData.clear();

    }

    reply->deleteLater();

    reply = nullptr;

  //   qDebug()<<replyData.size();

   //  qDebug()<<replyData;

    return replyData;

}

/*QByteArray http::post(const QString &strUrl, QByteArray data)

{

    const QUrl url = QUrl::fromUserInput(strUrl);

QByteArray replyData;

    QNetworkAccessManager m_qnam;

    QNetworkRequest qnr(url);

    qnr.setRawHeader("content-type","application/x-www-form-urlencoded");

    QNetworkReply* reply = m_qnam.post(qnr,data); //m_qnam是QNetworkAccessManager对象

    QEventLoop eventLoop;

    connect(reply, &QNetworkReply::finished, &eventLoop, &QEventLoop::quit);

    eventLoop.exec(QEventLoop::ExcludeUserInputEvents);

    QVariant statusCodeV =

    reply->attribute(QNetworkRequest::HttpStatusCodeAttribute);

    QVariant redirectionTargetUrl =

    reply->attribute(QNetworkRequest::RedirectionTargetAttribute);

    if (reply->error() == QNetworkReply::NoError)

    {

         replyData = reply->readAll();  // bytes

        //QString string(bytes); // string

        QString string = QString::fromUtf8(replyData);

        qDebug()<<string.size();

        string=string.mid(0,5000);

        qDebug()<<string;

    }

    else

    {

        qDebug()<<reply->errorString();

    }

    reply->deleteLater();

     qDebug()<<replyData.size();

     qDebug()<<replyData;

     QJsonParseError json_error;

     QJsonDocument parse_doucment = QJsonDocument::fromJson(replyData, &json_error);

     if(json_error.error == QJsonParseError::NoError)

     {

         if(parse_doucment.isObject())

         {

             QJsonObject obj = parse_doucment.object();

             if(obj.contains("info"))

             {

                 QJsonValue name_value = obj.take("info");

                 if(name_value.isString())

                 {

                     QString ID = name_value.toString();

                      qDebug()<<ID;

                  //   processs_data.append(ID);

                 }

                 else

                     {

                     qDebug()<<"777";

                 }

             }

             else{

                 qDebug()<<"444";

             }

         }

         else

         {

             qDebug()<<"333";

         }

     }

     else

     {

         qDebug()<<"00";

     }

    return replyData;

}*/

QStringList http::search(QString regulardata,QString data)
{

    QStringList searchdata;

    QRegularExpression regularExpression(regulardata);

        int index = 0;

        QRegularExpressionMatch match;

        do {

            match = regularExpression.match(data, index);

            if(match.hasMatch()) {

                index = match.capturedEnd();

                searchdata.append(match.captured(0));

               // qDebug()<<"("<<match.capturedStart()<<","<<index<<") "<<match.captured(0);

            }
            else {

                            break;

            }

        } while(index < data.length());

        //qDebug()<<searchdata;

        return searchdata;

}


QString http::date_form(QString time)
{
    QStringList year_month,day;
    QStringList temp;

    time.replace("年","-");
    time.replace("月","-");
    time.replace("日"," ");
    time.replace("号"," ");
    time.replace("&sim;","-");

    qDebug()<<time;
    year_month = search("(.*?)-",time);
    qDebug()<<year_month;
    if(year_month.size()==0||year_month[0].length()<5)
    {
        qDebug()<<"时间格式出错";
        return time;
    }

    if(year_month[1].length() == 2)
        year_month[1] = "0" + year_month[1];

    day = search("-(.*?) ",time);
    temp = search("-(.*?)-",day[0]);
    day[0].replace(temp[0],"");
    if(day[0].length() == 2)
        day[0] = "0" + day[0];

    temp = search("(.*?)-(.*?)-(.*?) ",time);
    time.replace(temp[0],year_month[0]+year_month[1]+day[0]+" ");
    //qDebug()<<time;

    return time;
}

QString http::date_format(QString time_data)//统一时间格式
{
    time_data.replace(" ","");//删除空格
    time_data.replace("/","-");//替换“/”为“-”
    QStringList temp_1;
    QStringList temp_2;
    QStringList temp_3;
    QString month;
    QString day1 , day2;
    temp_1 = search("年(.*?)月",time_data);
    temp_2 = search("月(.*?)日",time_data);
    temp_3 = search("月(.*?)号",time_data);

    if(temp_1.size()>0)
    {
        temp_1[0].replace("年","");//删去无用信息
        temp_1[0].replace("月","");
        for(int i = 1; i <= 9;i++)
        {
            if(temp_1[0]==QString::number(i))//补0
            {
                temp_1[0] = "0" + QString::number(i);
            }
        }
        month = "-"+temp_1[0]+"月";
    }
    else
    {
        //若非年月日格式，再进一步修正补零
        QString temp7 = time_data.at(6);
        QString temp8 = time_data.at(9);
        if(temp7=="-")
            time_data.insert(5,"0");//补0
        for(int i = 0; i <= 9;i++)
        {
            if(QString::compare(temp8,QString::number(i))==0)
            {
                break;
            }
            if(i==9)
            {
                time_data.insert(8,"0");//补0
            }
        }

        return time_data;
    }

    if(temp_2.size()>0)
    {
        temp_2[0].replace("月","");//删去无用信息
        temp_2[0].replace("日","");
        for(int i = 1; i <= 9;i++)
        {
            if(temp_2[0]==QString::number(i))//补0
            {
                temp_2[0] = "0" + QString::number(i);
            }
        }
        day1 = "-"+temp_2[0]+" ";
    }
    else
    {
        if(temp_3.size()>0)
        {
            temp_3[0].replace("月","");//删去无用信息
            temp_3[0].replace("号","");
            for(int i = 1; i <= 9;i++)
            {
                if(temp_3[0]==QString::number(i))//补0
                {
                    temp_3[0] = "0" + QString::number(i);
                }
            }
        }
         day2 = "-"+temp_3[0]+" ";
     }

    //替换
    QStringList temp_4 = search("年(.*?)月",time_data);
    for(int i = 0;i<temp_4.size();i++)
    {
        time_data.replace(temp_4[i],month);
    }

    QStringList temp_5 = search("月(.*?)日",time_data);
    for(int i = 0;i<temp_5.size();i++)
    {
        time_data.replace(temp_5[i],day1);
    }

    QStringList temp_6 = search("月(.*?)号",time_data);
    for(int i = 0;i<temp_6.size();i++)
    {
        time_data.replace(temp_6[i],day2);
    }



    return time_data;

}

